﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSS;
using Thuoc24h.BasePage;
using Thuoc24h.Data;
using Thuoc24h.Common;

namespace Thuoc24h.Home.Controls
{
    public partial class ShopCart : BaseUserControls
    {
        private List<ShopCartEntity> order;
        private long _totalPrice = 0;
        private long _priceProduct = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            MessageLtr.Visible = false;
            pnlBaokim.Visible = false;
            pnlInfo.Visible = false;
            if (!Page.IsPostBack)
            {
                CalendarExtender1.StartDate = DateTime.Now;
                btnPayBaoKim.ImageUrl = "http://developer.baokim.vn/uploads/baokim_btn/thanhtoanantoan-l.png";
                //  btnPayNganluong.ImageUrl = "https://www.nganluong.vn/data/images/buttons/11.gif";
                if (Request.UrlReferrer != null) ViewState["RefUrl"] = Request.UrlReferrer.ToString();
                if (Session["Order"] != null)
                {
                    order = (List<ShopCartEntity>)Session["Order"];
                    OrderProduct.DataSource = order;
                    OrderProduct.DataBind();



                    HasProductPLH.Visible = true;
                    NoProductPLH.Visible = false;
                }
                else
                {
                    HasProductPLH.Visible = false;
                    NoProductPLH.Visible = true;
                }


            }

            if (Session["Customer"] != null)
            {
                var user = (Customer)Session["Customer"];
                txtName.Text = user.Name;
                txtPhone.Text = user.Phone;
                txtAddress.Text = user.Address;
                txtEmail.Text = user.Email;


            }


        }


        protected void OrderProduct_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var quantity = e.Item.FindControl("txtQuantity") as TextBox;
            var price = e.Item.FindControl("lblPrice") as Label;
            if (long.Parse(quantity.Text) == 0)
            {
                quantity.Text = 1 + "";
            }
            if (quantity != null && price != null)
            {
                _priceProduct += (long.Parse(quantity.Text)) * long.Parse(price.Text.Replace(",", ""));
                lblTotalPrice.Text = _priceProduct.ToString("0,0");
            }
        }

        protected void OrderProduct_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            int index = e.ItemIndex;
            order = (List<ShopCartEntity>)Session["Order"];
            order.RemoveAt(index);
            if (order.Count == 0)
            {
                lblTotalPrice.Text = "0";
                Response.Redirect("~/trang-chu.aspx");
            }
            Session["Order"] = order;
            Session["PriceTag"] = order;
            OrderProduct.DataSource = null;
            OrderProduct.DataSource = order;
            OrderProduct.DataBind();
            Response.Redirect(Request.RawUrl);
        }
        protected void btnUpdateCart_Click(object sender, EventArgs e)
        {
            _totalPrice = 0;

            foreach (var item in OrderProduct.Items)
            {
                var quantity = item.FindControl("txtQuantity") as TextBox;
                var productID = item.FindControl("lblProductID") as Label;
                var price = item.FindControl("lblPrice") as Label;
                long itemPrice;
                if (!long.TryParse(quantity.Text.Replace(",", ""), out itemPrice))
                {
                    Response.Redirect("~/trang-chu.aspx");
                }
                if (quantity != null && price != null)
                {
                    _priceProduct += ((long.Parse(quantity.Text)) * long.Parse(price.Text.Replace(",", "")));
                    _totalPrice = _priceProduct;
                }

                var listOrder = (List<ShopCartEntity>)Session["Order"];
                if (listOrder.Count > 0)
                {
                    for (int i = 0; i < listOrder.Count; i++)
                    {
                        if (productID != null)
                        {
                            if (listOrder[i].ID == long.Parse(productID.Text))
                            {
                                if (quantity != null)
                                    listOrder[i].Quantity = int.Parse(quantity.Text);
                                if (price != null)
                                    listOrder[i].Price = double.Parse(price.Text.Replace(",", ""));
                            }
                        }
                    }
                }
                else
                {
                    lblTotalPrice.Text = "0";
                }
                Session["Order"] = listOrder;
                Session["PriceTag"] = listOrder;
            }
            lblTotalPrice.Text = _totalPrice.ToString("0,0");
            Response.Redirect(Request.RawUrl);
        }

        protected void btnBuyNext_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/trang-chu.aspx");
        }

        protected void btnCheckOut_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/thanh-toan.aspx");




        }
        protected void BtnPriceTag_Click(object sender, EventArgs e)
        {
            Session["PriceTag"] = Session["Order"];
            Response.Redirect("~/Bao-gia.aspx");
        }


        protected void btnPayBaoKim_OnClick(object sender, ImageClickEventArgs e)
        {
               CaptchaControl1.ValidateCaptcha(txtCaptcha.Text.Trim());
            if (CaptchaControl1.UserValidated)
            {

                string order_id = "INVOICE-" + AddOrder();
                string business = "medlife.vn@gmail.com";
                string total_amount = totalPrice().ToString();
                string shipping_fee = "0";
                string tax_fee = "10";
                string order_description = txtDetail.Text;
                string url_success = "http://thuoctot24h.com.vn/Thanh-toan-thanh-cong.aspx";
                string url_cancel = "http://thuoctot24h.com.vn";
                string url_detail = "";


                string Checksum;



                var payment = new BaoKimPayment();
                var url = payment.createRequestUrl(order_id, business, total_amount, shipping_fee, tax_fee,
                                                   order_description, url_success, url_cancel, url_detail);
                Session["Order"] = null;
                Response.Redirect(url);
            }
        }

        protected void btnPayNganluong_OnClick(object sender, ImageClickEventArgs e)
        {
            String return_url = "http://demo.nganluong.vn";// Địa chỉ trả về 
            String transaction_info = "Hãy lập trình thông tin của giao dịch của bạn vào đây";//Thông tin giao dịch
            String order_code = "Hãy lập trình mã hóa đơn của bạn vào đây";//Mã giỏ hàng 
            String receiver = "medlife.vn@gmail.com";//Tài khoản nhận tiền 
            String price = _totalPrice.ToString().FormatMoney();
            NL_Checkout nl = new NL_Checkout();
            String url;
            url = nl.buildCheckoutUrl(return_url, receiver, transaction_info, order_code, price);

        }


        private double totalPrice()
        {
            double? totals = 0;
            if (Session["Order"] != null)
            {
                var orders = (List<ShopCartEntity>)Session["Order"];
                OrderProduct.DataSource = orders;
                OrderProduct.DataBind();

                foreach (var order in orders)
                {
                    totals += order.Quantity * order.Price;

                }


            }
            return totals.ToDoubleReturn0();
        }
        private string AddOrder()
        {
            string codeinvoice = "";
            var invoice = new Invoice();
            invoice.BuyerName = txtName.Text;
            invoice.BuyerPhone = txtPhone.Text;
            invoice.BuyerAddress = txtAddress.Text;
            invoice.BuyerEmail = txtEmail.Text;
            var str = "";
            str = rdogiaohang.Checked ? "Hỏa tốc trong ngày/ 3 – 5 ngày" : "";
            str += rdoThoigian.Checked ? "Giờ hành chính/ngoài giờ" : "";

            var paymentType = "";

            if (ddlPayMethod.SelectedValue.Equals("1"))
            {
                paymentType = "Thanh toán an toàn qua bảo kim";
            } if (ddlPayMethod.SelectedValue.Equals("2"))
            {
                paymentType = "Thanh toán an toàn qua bảo kim";
            } if (ddlPayMethod.SelectedValue.Equals("3"))
            {
                paymentType = "Thanh toán an toàn qua bảo kim";
            }

            invoice.Note = "- Thời gian muốn gia hàng: " + str + "<br /> - Phương thức thanh toán:" + paymentType + "<br/>- Lưu ý cho Medlife khi giao hàng" + txtDetail.Text;
            invoice.CreatedDate = DateTime.Now;
            invoice.ReceiverAddress = txtReceiverAddress.Text;
            invoice.ReceiverEmail = txtReceiverEmail.Text;
            invoice.ReceiverPhone = txtReceiverPhone.Text;
            invoice.ReceiverName = txtReceiverName.Text;
            if (txtReceiverDate.Text != string.Empty)
            {
                invoice.ReceiveDate = Convert.ToDateTime(txtReceiverDate.Text);
            }

            invoice.Status = 0;
            context.Invoices.AddObject(invoice);
            if (context.SaveChanges() > 0)
            {

                if (Session["Order"] != null)
                {
                    order = (List<ShopCartEntity>)Session["Order"];
                    foreach (var item in order)
                    {
                        var orderDetail = new OrderDetail();
                        int idinvoice = invoice.Id;
                        codeinvoice = idinvoice.ToString();
                        orderDetail.InvoiceId = idinvoice;
                        orderDetail.ProductId = item.ID;
                        orderDetail.Quantity = item.Quantity;
                        orderDetail.Price = item.Price;
                        context.OrderDetails.AddObject(orderDetail);

                    }
                    context.SaveChanges();

                }

            }

            return codeinvoice;
        }



        protected void LoginBtn_OnClick(object sender, EventArgs e)
        {
            string username = UserNameTxt.Text.Trim();
            string pass = PasswordTxt.Text.Trim();

            var customer = context.Customers.FirstOrDefault(it => it.UserName == username && it.Password == pass);
            if (customer != null)
            {
                mpePopup.Hide();
                Session["UserName"] = username;
                Session["Customer"] = customer;
                Response.Redirect("/gio-hang.aspx");

            }

            else
            {

                MessageLtr.Visible = true;
                MessageLtr.Text = "Đăng nhập không thành công! Hãy kiểm tra lại.";
                mpePopup.Show();

            }
        }

        protected void btnThanhtoan_OnClick(object sender, EventArgs e)
        {
              CaptchaControl1.ValidateCaptcha(txtCaptcha.Text.Trim());
            if (CaptchaControl1.UserValidated)
            {
                if (AddOrder() != null)
                {
               Page.ClientScript.RegisterStartupScript(this.GetType(), "Thông báo", "alert('" + "Gửi liên hệ thành công" + "');", true);
                    
                }
            }
        }

        protected void ddlPayMethod_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlPayMethod.SelectedValue == "1")
            {
                pnlBaokim.Visible = true;
                pnlThanhtoan.Visible = false;
                pnlInfo.Visible = false;

            }
            if (ddlPayMethod.SelectedValue == "2")
            {
                pnlBaokim.Visible = false;
                pnlThanhtoan.Visible = true;
                pnlInfo.Visible = true;
            }
            if (ddlPayMethod.SelectedValue == "3")
            {
                pnlThanhtoan.Visible = true;
                pnlInfo.Visible = false;
            }
        }
    }
}